package array;

import java.util.Arrays;

class Arraylist {
    //默认容量为2
    public static final int capacity = 2;

    public int[] elem;
    public int usedSize;

    public Arraylist() {
        this.elem = new int[capacity];
    }


    public boolean contains(int data) {
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == data) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int data) {
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == data) {
                return i;
            }
        }
        return -1;
    }

    public int getInteger(int pos) {
        if (checkPos(pos)) {
            return elem[pos];
        }
        return -2;
    }

    public void setElem (int pos, int data){
        if (checkPos(pos)) {
            elem[pos] = data;
        }
    }

    public void remove (int pos) {
        if(pos <= usedSize - 1) {
            for (int i = pos; i < usedSize - 1; i++) {
                elem[i] = elem[i+1];
            }
            usedSize--;
        }
    }

    public int getSize () {
        return usedSize;
    }
    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.println(this.elem[i]);
        }
    }


    /**
     * 指定位置添加的函数
     * @param pos
     * @param data
     */
    public void add(int pos, int data) {
        try {
            if (checkPos(pos)) {
                if (!isFull()) {
                    elem = Arrays.copyOf(elem, elem.length + 1);
                }  //扩容执行一次就够
                for (int i = usedSize - 1; i < pos; i++) {
                    elem[usedSize] = elem[usedSize + 1];
                }
                elem[pos] = data;
                usedSize++;
            }
        } catch (PosIllegalException posIllegalException) {
            posIllegalException.printStackTrace();
        }
    }
    public boolean checkPos(int pos) {
        if (pos < 0 ||pos >this.usedSize) {
            throw new PosIllegalException();
        } else {
            return true;
        }
    }

    /**
     * 顺序添加函数 / 扩容函数
     *s@param i 添加的数据
     */
    public void add(int i) {
        if(!this.isFull()) {
            elem = Arrays.copyOf(elem, elem.length + 1);
        }
        elem[usedSize++] = i;
    }

    public boolean isFull() {
        if (this.usedSize >= this.elem.length) {
            return true;
        }
        return false;
    }
}
